#!/usr/bin/bash
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2020 Joyent, Inc.
#

#
# Attempt to clobber an illumos build. We override $MAKE in the
# environment to explicitly point at the bootstrap dmake that we install
# as part of ./configure.
#
set -o pipefail

ci_wsroot=$(cd $(dirname $0)/../; pwd)
ci_arg0=$(basename $0)
ci_illumos="$ci_wsroot/projects/illumos/usr/src"
ci_dmake="/opt/local/bin/dmake"

export PATH=/usr/bin:/usr/sbin:/opt/local/bin:/opt/local/sbin

function ci_fatal
{
	local msg="$*"
	[[ -z "$msg" ]] && msg="failed"
	printf '%s: ERROR: %s\n' "$ci_arg0" "$msg" >&2
	exit 1
}

#
# We assume that this will be run from the root of smartos-live. If
# we're not being run from there, error, since we assume paths. We use
# the presence of the file default.configure-projects for this, since it's
# a relatively unique file in the top level.
#
function ci_verify_root
{
	[[ ! -f "$ci_wsroot/default.configure-projects" ]] && ci_fatal \
	    "determined workspace root as $ci_wsroot: but missing indicating" \
	    "file default.configure-projects"
}

#
# Do the hard work of actually running dmake clobber. We purposefully
# allow its exit status to propagate out of here.
#
function ci_do_clobber
{
	echo "Clobbering $ci_wsroot/projects/illumos"
	export MAKE="$ci_dmake"
	$ci_illumos/tools/scripts/bldenv $ci_illumos/../../illumos.sh \
	    'cd $CODEMGR_WS/usr/src && dmake clobber'
}

ci_verify_root
ci_do_clobber
